package de.windeln.google.service;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.Assert;

import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.services.analytics.Analytics;
import com.google.api.services.analytics.model.McfData;



public class McfService {

	/**
	 * Main demo. This first initializes an analytics service object. It then
	 * uses the Google Analytics Management API to get the first profile ID for
	 * the authorized user. It then uses the MCF Reporting API to retrieve the
	 * required dimensions and metrics. Finally the results are printed to the
	 * screen. If an API error occurs, it is printed here.
	 * 
	 * @param args
	 *            command line args.
	 */

	public McfService(DataSource dataSource) {
		this.dataSource = dataSource;
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	private DataSource dataSource;
	private JdbcTemplate jdbcTemplate;

//	@Required
//	public void setDataSource(DataSource dataSource) {
//		this.jdbcTemplate = new JdbcTemplate(dataSource);
//	}

	public void main() {
		Assert.notNull(dataSource);
		Assert.notNull(jdbcTemplate);
		
		String SQL = "update Student set age = ? where id = ?";
		jdbcTemplate.update(SQL, 1, "quatsch");

		AccessAdministration accessAdmin = new AccessAdministration();
		ReportAccess reportAccess = new ReportAccess();

		try {
			Analytics analytics = accessAdmin.initializeAnalytics();
			String profileId = accessAdmin.getFirstProfileId(analytics);

			if (profileId == null) {
				System.err.println("No profiles found.");
			} else {
				McfData mcfData = reportAccess.executeDataQuery(analytics,
						profileId);
				reportAccess.printDataTable(mcfData);
			}

		} catch (GoogleJsonResponseException e) {
			System.err.println("There was a service error: "
					+ e.getDetails().getCode() + " : "
					+ e.getDetails().getMessage());
		} catch (Throwable t) {
			t.printStackTrace();
		}
	}

}
